package com.shq.ex1;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.TextView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.BindView;

public class DicitionaryActivity extends AppCompatActivity implements TextWatcher {

    @BindView(R.id.dword)
    AutoCompleteTextView dword;
    @BindView(R.id.dcheck)
    Button dcheck;
    private SQLiteDatabase db = null;

    //权限
    private boolean granted = false;
    String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
    List<String> mPermissionList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dicitionary);
        ButterKnife.bind(this);

        checkPermission();
        if(ActivityCompat.checkSelfPermission(DicitionaryActivity.this,permissions[0])
                == PackageManager.PERMISSION_GRANTED){
            granted = true;
        }
        while (!granted){
            SystemClock.sleep(500);
            Log.i("词典","等待");
        };
        boolean sdcardExits = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED
        );
        String path = null;
        if(sdcardExits) {
            path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
                    + "dictionary";
        }else{
            path = "/sdcard";
        }
        String databaseName = "dictionary.db";
        String databasePath = path + File.separator + databaseName;
        if(!new File(path).exists()){
            new File(path).mkdirs();
        }
        if(!(new File(databasePath)).exists()){
            try {
                InputStream is = getResources().openRawResource(R.raw.dictionary);
                FileOutputStream fos = new FileOutputStream(databasePath);
                byte[] buffer = new byte[is.available()];
                int count = 0;
                while ((count = is.read(buffer))>0){
                    fos.write(buffer,0,count);
                }
                fos.close();
                is.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Log.e("词典","找不到文件");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //打开数据库
        db = SQLiteDatabase.openOrCreateDatabase(databasePath,null);

        dcheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String sql = "select chinese from t_words where english = ?";
                Cursor cursor = db.rawQuery(sql,new String[]{dword.getText().toString().trim()});
                String result = "Not Found";
                if(cursor.getCount()>0){
                    cursor.moveToFirst();
                    result = cursor.getString(cursor.getColumnIndex("chinese"));
                }
                new AlertDialog.Builder(DicitionaryActivity.this).setTitle(
                    "查询结果").setMessage(result).setPositiveButton(
                    "           关闭",null).show();
            }
        });
        dword.addTextChangedListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        Cursor cursor = db.rawQuery("select english as _id from t_words where english like ?"
        ,new String[]{s.toString()+"%"});
        DictionaryAdapter adapter = new DictionaryAdapter(DicitionaryActivity.this,
                cursor,true);
        dword.setAdapter(adapter);
    }

    /**
     * 判断哪些权限未授予
     */
    private void checkPermission() {
        mPermissionList.clear();
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(DicitionaryActivity.this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }

        if (!mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了
            //请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(DicitionaryActivity.this, permissions, 1);
        }
    }

    /**
     * 请求权限的回调
     *
     * 参数1：requestCode-->是requestPermissions()方法传递过来的请求码。
     * 参数2：permissions-->是requestPermissions()方法传递过来的需要申请权限
     * 参数3：grantResults-->是申请权限后，系统返回的结果，PackageManager.PERMISSION_GRANTED表示授权成功，PackageManager.PERMISSION_DENIED表示授权失败。
     * grantResults和permissions是一一对应的
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults.length > 0) {
            granted = grantResults[0] == PackageManager.PERMISSION_GRANTED;//是否授权，可以根据permission作为标记
        }
    }

    public class DictionaryAdapter extends CursorAdapter
    {
        private LayoutInflater layoutInflater;
        @Override
        public CharSequence convertToString(Cursor cursor)
        {
            return cursor == null ? "" : cursor.getString(cursor
                    .getColumnIndex("_id"));
        }

        private void setView(View view, Cursor cursor)
        {
            TextView tvWordItem = (TextView) view;
            tvWordItem.setText(cursor.getString(cursor.getColumnIndex("_id")));
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor)
        {
            setView(view, cursor);
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent)
        {
            View view = layoutInflater.inflate(R.layout.word_list, null);
            setView(view, cursor);
            return view;
        }

        public DictionaryAdapter(Context context, Cursor c, boolean autoRequery)
        {
            super(context, c, autoRequery);
            layoutInflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
    }
}
